package sort

import (
	"fmt"
	"sort"
)

func Sort_1() {
	// int切片排序
	s := []int{2, 31, 3324, 56, 1, 2, 4, 3}
	sort.Ints(s)
	fmt.Printf("s: %v\n", s)

	// float切片排序
	f := []float64{1.1, 8.8, 5.5, 3.3, 2.2}
	sort.Float64s(f)
	fmt.Printf("f: %v\n", f)

	//字符串排序
	ss := sort.StringSlice{"100", "42", "41", "3", "2"}
	fmt.Println(ss)
	sort.Strings(ss)
	fmt.Println(ss)

	ss = sort.StringSlice{"d", "ac", "c", "ab", "e"}
	fmt.Println(ss)
	sort.Strings(ss)
	fmt.Println(ss)

	// 汉字按照字节数组排序
	ss = sort.StringSlice{"啊", "博", "次", "得", "饿", "周"}
	fmt.Println(ss)
	sort.Strings(ss)
	fmt.Println(ss)

	for _, v := range ss {
		fmt.Printf("v: %v\n", []byte(v))
	}

}

/*

	自定义排序

*/

// 无符号整型
type UIntSlice []uint

// 绑定 Interface接口
func (uslice UIntSlice) Len() int {
	return len(uslice)
}

func (uslice UIntSlice) Less(i, j int) bool {
	fmt.Println(i, j, uslice[i] < uslice[j], uslice)
	return uslice[i] < uslice[j]
}

func (uslice UIntSlice) Swap(i, j int) {
	uslice[i], uslice[j] = uslice[j], uslice[i]
}

func SortUInt() {
	u := []uint{1, 8, 5, 3}
	sort.Sort(UIntSlice(u))
	fmt.Println(u)
}

// int数组
type IntArrSlice [][]int

func (intArr IntArrSlice) Len() int {
	return len(intArr)
}

func (intArr IntArrSlice) Less(i, j int) bool {
	return intArr[i][1] < intArr[j][1]
}

func (intArr IntArrSlice) Swap(i, j int) {
	intArr[i], intArr[j] = intArr[j], intArr[i]
}

func SortArrSlice() {
	ias := IntArrSlice{{1, 4}, {9, 3}, {7, 5}}
	fmt.Println(ias)
	sort.Sort(ias)
	fmt.Println(ias)
}

// map
type MapSlice []map[string]float64

func (mapSlice MapSlice) Len() int {
	return len(mapSlice)
}

func (mapSlice MapSlice) Less(i, j int) bool {
	return mapSlice[i]["a"] < mapSlice[j]["a"]
}

func (mapSlice MapSlice) Swap(i, j int) {
	mapSlice[i], mapSlice[j] = mapSlice[j], mapSlice[i]
}

func SortMapSlice() {
	ms := MapSlice{
		{"a": 4, "b": 12},
		{"a": 3, "b": 11},
		{"a": 5, "b": 10},
	}
	fmt.Println(ms)
	sort.Sort(ms)
	fmt.Println(ms)
}

// 自定义结构体

type People struct {
	name string
	age  uint
}

type PeopleSlice []People

func (peopleSlice PeopleSlice) Len() int {
	return len(peopleSlice)
}

func (peopleSlice PeopleSlice) Less(i, j int) bool {
	return peopleSlice[i].age < peopleSlice[j].age
}

func (peopleSlice PeopleSlice) Swap(i, j int) {
	peopleSlice[i], peopleSlice[j] = peopleSlice[j], peopleSlice[i]
}

func SortStructSlice() {
	ps := PeopleSlice{
		{name: "n1", age: 12},
		{name: "n2", age: 11},
		{name: "n3", age: 10},
	}
	fmt.Println(ps)
	sort.Sort(ps)
	fmt.Println(ps)
}
